package com.example.demofdfs.example.queue;

import java.util.Comparator;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TaskQueue {
	
	static Logger log = LoggerFactory.getLogger(TaskQueue.class);
	
	private Lock lock = new ReentrantLock();
	private Condition condition = lock.newCondition();
	
	
	private static TaskQueue instance = new TaskQueue();
	private static final BlockingQueue<Task> TASK_QUEUE = new PriorityBlockingQueue<>(10, new Comparator<Task>() {
		@Override
		public int compare(Task o1, Task o2) {
			return (int) (o1.getTime() - o2.getTime());
		}
	});
	
	private TaskQueue() {
	}


	public static void add(Task task) {
		instance.lock.lock();
		try {
			TASK_QUEUE.put(task);
			log.info("添加任务完成..." + task.getName());
			instance.condition.signal();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			instance.lock.unlock();
		}
		
	}
	
	public static Task get() {
		Task t = null;
		
		while(true) {
			instance.lock.lock();
			if (TASK_QUEUE.isEmpty()) {
				try {
					instance.condition.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			try {
				t = TASK_QUEUE.peek();
				long time = t.getTime();
				long l = time - System.currentTimeMillis();
				if (l < 0 || l == 0) {
					return TASK_QUEUE.take();
				} else {
					log.info("任务等待下发...." + t.getName());
					instance.condition.await(l, TimeUnit.MILLISECONDS);
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			} finally {
				instance.lock.unlock();
			}
		}
	}
	
}
